package com.xs.client;

import java.io.IOException;
import java.util.Date;
import java.util.Scanner;

import com.alibaba.fastjson.JSON;
import com.xs.client.handler.ClientHandler;
import com.xs.entity.LonginEntity;
import com.xs.entity.Message;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Client extends Thread {

	private int port = 9999;
	private String host = "127.0.0.1";

	private EventLoopGroup workGroup = new NioEventLoopGroup();

	
	private String userName ="";
	
	private Message msg;

	/**
	 * 
	 */
	public Client(Message msg) {
		this.msg = msg;
	}

	public void run() {
		Bootstrap boot = new Bootstrap();
		boot.group(workGroup);
		boot.channel(NioSocketChannel.class);
		boot.option(ChannelOption.TCP_NODELAY, true);
		boot.handler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel ch) throws Exception {

				ChannelPipeline pipeline = ch.pipeline();
				pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
				pipeline.addLast(new StringEncoder());
				pipeline.addLast(new StringDecoder());
				pipeline.addLast(new ClientHandler());

				;
			}
		});
		try {

			/*
			 * ChannelFuture f = boot.connect(host, port).sync();
			 * 
			 * 
			 * for(int i = 0 ;i<10;i++){
			 * 
			 * 
			 * f.channel().writeAndFlush("hello"+i);
			 * 
			 * }
			 */

			// Wait until the connection is closed.
			// f.channel().closeFuture().sync();

			Channel ch = boot.connect(host, port).sync().channel();

			//ch.writeAndFlush(JSON.toJSONString(msg) + "\r\n");
			
			try {
				LonginEntity  longinEntity = login();
				ch.writeAndFlush(JSON.toJSONString(longinEntity) + "\r\n");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			
			ch.closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			workGroup.shutdownGracefully();
		}

	}

	public LonginEntity login() throws IOException {
		Scanner scan = new Scanner(System.in);
	    String read = scan.nextLine();
		LonginEntity loginMsg = new LonginEntity();
		loginMsg.setUserName(read);
		loginMsg.setDate(new Date());
		userName = read;
		return loginMsg;

	}
	
	

	
}
